package com.lksoft.bz.action;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import com.lksoft.bz.Bz;
import com.lksoft.bz.StitchPattern;
import com.lksoft.bz.StitchPatternSerializer;

public class OpenAction extends AbstractAction {
	private static final long serialVersionUID = -1672017718776871293L;
	
	private Bz bz;
	
	/** Currently supported file formats */
	String[] supportedFormats = { StitchPatternSerializer.STPL_EXT, StitchPatternSerializer.STP_EXT };
	
	/**
	 * @param bz The program
	 * @throws IOException 
	 */
	public OpenAction(Bz bz, String iconPath) throws IOException{
		super("", new ImageIcon(ImageIO.read(Bz.class.getResourceAsStream(iconPath)).getScaledInstance(32, 32, Image.SCALE_SMOOTH)));
		this.bz = bz;

		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		putValue(MNEMONIC_KEY, KeyEvent.VK_O);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// First ask for save
		if( !bz.askForSave() ) return;
		
		// Show file chooser
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setMultiSelectionEnabled(false);
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				String fmtString ="";
				for(String s : supportedFormats){
					if( s != supportedFormats[0] ) fmtString += ", ";
					fmtString += "*"+s;
				}
				
				return "Stitch pattern("+fmtString+")";
			}
			@Override
			public boolean accept(File f) {
				if( f.isDirectory() ) return true;
				
				for( String s : supportedFormats ){
					if( f.getName().endsWith(s) ) return true;
				}
				
				return false;
			}
		});
		
		int res = fileChooser.showOpenDialog(bz.getFrame());
		
		if( res == JFileChooser.APPROVE_OPTION ){
			// Read selected file
			StitchPattern pattern = StitchPatternSerializer.readStitchPattern(fileChooser.getSelectedFile());
			if( pattern != null ) bz.setStitchPattern(pattern, fileChooser.getSelectedFile());
			else JOptionPane.showMessageDialog(bz.getFrame(), Bz.getUIString("messages.errors.cantopen"));
		}
	}

}
